// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package io

import (
	"errors"
	"exp/mem"
	"exp/unicode/utf8"
)

// A MemReader implements the Reader, ReaderAt, WriterTo, Seeker,
// ByteScanner, and RuneScanner interfaces by reading from
// a mem.RO.
type MemReader struct {
	s        mem.RO
	i        int // current reading index
	prevRune int // index of previous rune; or < 0
}

// Len returns the number of bytes of the unread portion of the
// slice.
func (r *MemReader) Len() int {
	if r.i >= r.s.Len() {
		return 0
	}
	return r.s.Len() - r.i
}

func (r *MemReader) Read(b mem.RW) (n int, err error) {
	if b.Len() == 0 {
		return 0, nil
	}
	if r.i >= r.s.Len() {
		return 0, EOF
	}
	n = b.CopyFrom(r.s.SliceFrom(r.i))
	r.i += n
	r.prevRune = -1
	return
}

func (r *MemReader) ReadAt(b mem.RW, off int64) (n int, err error) {
	if off < 0 {
		return 0, errors.New("bytes: invalid offset")
	}
	if off >= int64(r.s.Len()) {
		return 0, EOF
	}
	n = b.CopyFrom(r.s.SliceFrom(int(off)))
	if n < b.Len() {
		err = EOF
	}
	return
}

func (r *MemReader) ReadByte() (b byte, err error) {
	if r.i >= r.s.Len() {
		return 0, EOF
	}
	b = r.s.At(r.i)
	r.i++
	r.prevRune = -1
	return
}

func (r *MemReader) UnreadByte() error {
	if r.i <= 0 {
		return errors.New("bytes.Reader: at beginning of slice")
	}
	r.i--
	r.prevRune = -1
	return nil
}

func (r *MemReader) ReadRune() (ch rune, size int, err error) {
	if r.i >= r.s.Len() {
		return 0, 0, EOF
	}
	r.prevRune = r.i
	if c := r.s.At(r.i); c < utf8.RuneSelf {
		r.i++
		return rune(c), 1, nil
	}
	ch, size = utf8.DecodeRune(r.s.SliceFrom(r.i))
	r.i += size
	return
}

func (r *MemReader) UnreadRune() error {
	if r.prevRune < 0 {
		return errors.New("bytes.Reader: previous operation was not ReadRune")
	}
	r.i = r.prevRune
	r.prevRune = -1
	return nil
}

// Seek implements the Seeker interface.
func (r *MemReader) Seek(offset int64, whence int) (int64, error) {
	var abs int64
	switch whence {
	case 0:
		abs = offset
	case 1:
		abs = int64(r.i) + offset
	case 2:
		abs = int64(r.s.Len()) + offset
	default:
		return 0, errors.New("bytes: invalid whence")
	}
	if abs < 0 {
		return 0, errors.New("bytes: negative position")
	}
	if abs >= 1<<31 {
		return 0, errors.New("bytes: position out of range")
	}
	r.i = int(abs)
	return abs, nil
}

// WriteTo implements the WriterTo interface.
func (r *MemReader) WriteTo(w Writer) (n int64, err error) {
	r.prevRune = -1
	if r.i >= r.s.Len() {
		return 0, nil
	}
	b := r.s.SliceFrom(r.i)
	m, err := w.Write(b)
	if m > b.Len() {
		panic("bytes.Reader.WriteTo: invalid Write count")
	}
	r.i += m
	n = int64(m)
	if m != b.Len() && err == nil {
		err = ErrShortWrite
	}
	return
}

// NewReader returns a new MemReader reading from b.
func NewReader(b mem.RO) *MemReader { return &MemReader{b, 0, -1} }
